package com.frogs.ucenter.v1.service.impl;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.UrlUtil;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.ApplicablePlatformEnum;
import com.frogs.system.util.MailingEnum;
import com.frogs.system.util.ModifyWayEnum;
import com.frogs.system.util.OpenPlatformEnum;
import com.frogs.system.util.PrivateKey;
import com.frogs.system.util.SmsPartnerEnum;
import com.frogs.system.util.UserAccountAuthorizedStatusEnum;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.system.util.UserMessageStatusEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.component.SmsHelper;
import com.frogs.ucenter.component.VelocityMailSupportHelper;
import com.frogs.ucenter.dao.FamilyBaseInfoDao;
import com.frogs.ucenter.dao.UserLevelInfoDao;
import com.frogs.ucenter.dao.UserOpenPlatformInfoDao;
import com.frogs.ucenter.dao.UserPasswordModifyLogDao;
import com.frogs.ucenter.dao.WechatUserBaseInfoDao;
import com.frogs.ucenter.dao.WechatUserPhoneDao;
import com.frogs.ucenter.entity.FamilyBaseInfo;
import com.frogs.ucenter.entity.TaiKangUserInfo;
import com.frogs.ucenter.entity.UserAccountInfo;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.entity.UserMessageSmsVerifyCode;
import com.frogs.ucenter.entity.UserOpenPlatformInfo;
import com.frogs.ucenter.entity.UserPasswordModifyLog;
import com.frogs.ucenter.entity.WechatUserBaseInfo;
import com.frogs.ucenter.entity.WechatUserPhone;
import com.frogs.ucenter.util.DataCacheKey;
import com.frogs.ucenter.util.WebSiteEnum;
import com.frogs.ucenter.v1.request.OpenPlatformBindAndLoginRequest;
import com.frogs.ucenter.v1.request.OpenPlatformLoginRequest;
import com.frogs.ucenter.v1.request.OpenPlatformSendActivateEmailRequest;
import com.frogs.ucenter.v1.request.SmsSendDynamicPasswordRequest;
import com.frogs.ucenter.v1.request.UserAccountAuthorizationUpdateRequest;
import com.frogs.ucenter.v1.request.UserAccountDetailRequest;
import com.frogs.ucenter.v1.request.UserAccountEmailUpdateRequest;
import com.frogs.ucenter.v1.request.UserAccountInfoAddRequest;
import com.frogs.ucenter.v1.request.UserAccountInfoAutoRegisterRequest;
import com.frogs.ucenter.v1.request.UserAccountInfoListRequest;
import com.frogs.ucenter.v1.request.UserAccountInfoUpdateRequest;
import com.frogs.ucenter.v1.request.UserAccountNoviceUpdateRequest;
import com.frogs.ucenter.v1.request.UserBindEmailRequest;
import com.frogs.ucenter.v1.request.UserBindPhoneRequest;
import com.frogs.ucenter.v1.request.UserLoginByDynamicPasswordRequest;
import com.frogs.ucenter.v1.request.UserLoginNoPasswordRequest;
import com.frogs.ucenter.v1.request.UserLoginRequest;
import com.frogs.ucenter.v1.request.UserLogoutRequest;
import com.frogs.ucenter.v1.request.UserLostpasswordByAccountRequest;
import com.frogs.ucenter.v1.request.UserLostpasswordByEmailRequest;
import com.frogs.ucenter.v1.request.UserPasswordUpdateRequest;
import com.frogs.ucenter.v1.request.UserResetPasswordByPhoneRequest;
import com.frogs.ucenter.v1.request.UserResetPasswordRequest;
import com.frogs.ucenter.v1.request.UserUnbindEmailRequest;
import com.frogs.ucenter.v1.request.UserUnbindPhoneRequest;
import com.frogs.ucenter.v1.request.UserVerifyBindPhoneRequest;
import com.frogs.ucenter.v1.request.UserVerifyEmailRequest;
import com.frogs.ucenter.v1.request.UserVerifyNameRequest;
import com.frogs.ucenter.v1.request.UserVerifyPhoneRequest;
import com.frogs.ucenter.v1.request.UserVerifyRequest;
import com.frogs.ucenter.v1.request.WechatUserInfoRequest;
import com.frogs.ucenter.v1.request.WechatUserInfoUpdateRequest;
import com.frogs.ucenter.v1.request.WechatUserPhoneBindRequest;
import com.frogs.ucenter.v1.request.WechatUserPhoneUnBindRequest;
import com.frogs.ucenter.v1.request.WechatUserVerifyPhoneRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.OpenPlatformBindAndLoginResponse;
import com.frogs.ucenter.v1.response.OpenPlatformLoginResponse;
import com.frogs.ucenter.v1.response.PageListResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.response.UpdateResponse;
import com.frogs.ucenter.v1.response.UserAccountDetailResponse;
import com.frogs.ucenter.v1.response.UserLoginResponse;
import com.frogs.ucenter.v1.response.UserLostpassByAccountResponse;
import com.frogs.ucenter.v1.service.UserAccountInfoService;
import com.frogs.ucenter.v1.service.platform.center.PlatformOperationCenter;
import com.frogs.ucenter.v1.util.ApiConstants;

/**
 *
 * @author lijian
 * @version 2014年3月25日 - 上午11:33:40
 */
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userAccountInfoService")
public class UserAccountInfoServiceImpl extends UserBaseServiceImpl implements UserAccountInfoService{
	
	private static final Logger log = LoggerFactory.getLogger(UserAccountInfoServiceImpl.class);

	@Resource
	protected FamilyBaseInfoDao familyBaseInfoDao;
	@Resource
	private UserLevelInfoDao userLevelInfoDao;
	@Resource
	private WechatUserBaseInfoDao wechatUserBaseInfoDao;
	@Resource
	private WechatUserPhoneDao wechatUserPhoneDao;
	@Resource
	private VelocityMailSupportHelper velocityMailSupportHelper;
	@Resource
	private SmsHelper smsHelper;
	@Resource
	private UserPasswordModifyLogDao passwordLogDao;
	@Resource
	private UserOpenPlatformInfoDao userOpenPlatformInfoDao;

//	@Resource(name="mailingHelper")
//	private MailingHelper mailingHelper;
	
	@Resource(name=ApiConstants.VERSION + "platformOperationCenter")
    private PlatformOperationCenter platformOperationCenter;
	
	/**
	 * 注册
	 */
	@Override
	public synchronized Response insert(Request request) throws Exception  {
		AddResponse<UserBaseAccountInfo> response = new AddResponse<UserBaseAccountInfo>();
		Long startTime = System.currentTimeMillis();
		log.info("func[insert] request["+request+"] desc[start]");
		try {
			UserAccountInfoAddRequest accountInfoAddRequest = (UserAccountInfoAddRequest) request;
			this.registerAsync(accountInfoAddRequest);
			String ip = accountInfoAddRequest.getIp();
			String userName = accountInfoAddRequest.getUsername();
			String nickName = accountInfoAddRequest.getNickname();
			String realName = accountInfoAddRequest.getRealName();
			Map<String, Object> obj = new HashMap<String, Object>();
			this.verifyUserName(userName, nickName, obj);
			String email = (String) obj.get("email");
			String phone = (String) obj.get("phone");
			String accountName = (String) obj.get("accountName");
			
			String passwd = accountInfoAddRequest.getPasswd();
			Integer applicablePlatformId = accountInfoAddRequest.getApplicablePlatformId();
			String expandCode = accountInfoAddRequest.getExpandCode();
			UserAccountInfo userAccountInfo = this.insertUser(accountName, email, phone, applicablePlatformId, expandCode, passwd);
//			if (!StringUtil.isEmpty(email)) {
//				RecordResultType record = mailingHelper.addMailReciever(email,null);
//				//添加用户邮箱
//				if(null != record && !RecordResultTypeStatus._ERROR.equalsIgnoreCase(record.getStatus().getValue())) {
//					//添加成功发送欢迎邮件
//					mailingHelper.sendWelcomeMail(email);
//				}
//			}
				
			//TODO 暂时屏蔽 发送邮箱验证串
//			if (!StringUtil.isEmpty(email)) {
//				this.sendVerifyEmail(userAccountInfo);
//			}
			//相应初始化相关的表
			this.initializeOther(userAccountInfo, nickName, realName);
			UserBaseAccountInfo userBaseAccountInfo = creatVerify(userAccountInfo, ip);
			response.setInfo(userBaseAccountInfo);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		Long endTime = System.currentTimeMillis();
		log.info("func[insert] time["+(endTime-startTime)+"] request["+request+"] desc[end]");
		return response;
	}
	
	/**
	 * 检查用户注册缓存同步状态,用于防止表单重复提交导致数据重复添加
	 * 
	 * @param accountInfoAddRequest
	 */
	private synchronized void registerAsync(UserAccountInfoAddRequest accountInfoAddRequest)  throws Exception {
		String cacheKey = DataCacheKey.registerAsyncMapkey + accountInfoAddRequest.getUsername() + "_" + accountInfoAddRequest.getApplicablePlatformId(); 
		do {
			if(null != cache.get(cacheKey)) {
				log.info("func[registerAsync] 用户注册操作进程未完成，请求频率过频繁");
				throw new ServiceOperationException("该注册请求正在进行中，请稍等");
			} else {
				cache.put(cacheKey, 3, 3);
				return;
			}
		}while(true);
	}
	
	/**
	 * 注册用户名的验证
	 * 
	 * @param userName
	 * @param obj
	 */
	private void verifyUserName(String userName, String nickName, Map<String, Object> obj)  throws Exception {
		String email = "";
		String phone = "";
		String accountName = "";
		if (StringUtil.isEmail(userName)) {
			email = userName;
			accountName = nickName;
		} else if (StringUtil.isMobilePhone(userName)) {
			phone = userName;
			accountName = nickName;
		} else {
			accountName = userName;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		int count = 0;
		if (StringUtil.isEmpty(accountName)) {
			accountName = createAccountName();
		} else {
			if (accountName.length() < 2 || accountName.length() > 20) {
				throw new ServiceOperationException("用户名的长度在2-20位");
			}
			if (!Pattern.matches("^[a-zA-Z0-9_\u4e00-\u9fa5]+$", accountName)) {
				throw new ServiceOperationException("用户名只能是中文，字母，数字，下划线组成");
			}
			param.put("eqAccountName", accountName);
			count = userAccountInfoDao.selectCountByMap(param);
			if (count > 0) {
				if(StringUtil.isEmail(userName) || StringUtil.isMobilePhone(userName)) {
					accountName = createAccountName();
				} else {
					throw new ServiceOperationException("该用户名已经存在");
				}
			}
		}
		if (!StringUtil.isEmpty(email) && !StringUtil.isEmail(email)) {
			throw new ServiceOperationException("邮箱格式有误");
		}
		if (!StringUtil.isEmpty(phone) && !StringUtil.isMobilePhone(phone)) {
			throw new ServiceOperationException("手机号码格式有误");
		}
		
		if (!StringUtil.isEmpty(email)) {
			param.clear();
			param.put("eqEmail", email);
			param.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			count = userAccountInfoDao.selectCountByMap(param);
			if (count > 0) {
				throw new ServiceOperationException("该邮箱已经被验证过");
			}
		}
		if (!StringUtil.isEmpty(phone)) {
			param.clear();
			param.put("eqPhone", phone);
			param.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			count = userAccountInfoDao.selectCountByMap(param);
			if (count > 0) {
				throw new ServiceOperationException("该手机号码已经被验证过");
			}
		}
		obj.put("email", email);
		obj.put("phone", phone);
		obj.put("accountName", accountName);
	}
	
	/**
	 * 自动注册
	 * 
	 * @param request
	 * @return
	 */
	@Override
	public Response autoRegister(Request request)  throws Exception {
		AddResponse<UserBaseAccountInfo> response = new AddResponse<UserBaseAccountInfo>();
		try {
			UserAccountInfoAutoRegisterRequest autoRegisterRequest = (UserAccountInfoAutoRegisterRequest) request;
			String openId = autoRegisterRequest.getOpenId();
			Integer openPlatformId = autoRegisterRequest.getOpenPlatformId();
			
			Map<String, Object> params = new HashMap<String, Object>();
			
			if (StringUtil.isEmpty(openId)) {
				throw new ServiceOperationException("openId不能为空");
			}
			UserAccountInfo userAccountInfo = new UserAccountInfo();
			params.put("eqOpenId", openId);
			params.put("eqOpenPlatformId", openPlatformId);
			PageList<UserOpenPlatformInfo> list = userOpenPlatformInfoDao.selectByMap(params, false);
			int count = list.size();
			if (count > 0) {
				int userId = list.get(0).getUserId();
				userAccountInfo = userAccountInfoDao.selectById(userId);
			} else {
				this.autoRegisterAsync(autoRegisterRequest);
				if (openPlatformId == OpenPlatformEnum.WECHAT_MALL.getId() ||
						openPlatformId == OpenPlatformEnum.WECHAT_HDC.getId()) {
					userAccountInfo = registerWechatUser(autoRegisterRequest);
				} else if (openPlatformId == OpenPlatformEnum.CHUNYUYISHENG.getId()) {
					userAccountInfo = registerChunyuUser(autoRegisterRequest);
				} else if (openPlatformId == OpenPlatformEnum.TAIKANG.getId()) {
					userAccountInfo = registerTaiKangUser(autoRegisterRequest);
				} else if (openPlatformId == OpenPlatformEnum.TCL.getId()) {
					userAccountInfo = registerTCLUser(autoRegisterRequest);
				} else if (openPlatformId == OpenPlatformEnum.PINGAN.getId()) {
					userAccountInfo = registerPinganUser(autoRegisterRequest);
				} else {
					throw new ServiceOperationException("注册失败");
				}
			}
			UserBaseAccountInfo userBaseAccountInfo = this.creatVerify(userAccountInfo, "");
			response.setInfo(userBaseAccountInfo);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						 request, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 春雨医生用户注册
	 * 
	 * @param autoRegisterRequest
	 * @param userAccountInfo
	 */
	private UserAccountInfo registerChunyuUser(UserAccountInfoAutoRegisterRequest autoRegisterRequest) {
		UserAccountInfo userAccountInfo = new UserAccountInfo();
		int count = 0;
		PageList<UserAccountInfo> result = new PageList<UserAccountInfo>();
		if (!StringUtil.isEmpty(autoRegisterRequest.getPhone())) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqPhone", autoRegisterRequest.getPhone());
			params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			result = userAccountInfoDao.selectByMap(params, false);
			count = result.size();
		}
		String accountName = createAccountName();
		if(count == 0){
			userAccountInfo = insertUser(accountName, "", autoRegisterRequest.getPhone(), autoRegisterRequest.getApplicablePlatformId(), 
					autoRegisterRequest.getExpandCode(), "");
			this.initializeOther(userAccountInfo, "");
		} else{
			userAccountInfo = result.get(0);
			if (this.isBindOpenPlatformUser(userAccountInfo.getId(), autoRegisterRequest.getOpenPlatformId())) {
				userAccountInfo = insertUser(accountName, "", "", autoRegisterRequest.getApplicablePlatformId(), autoRegisterRequest.getExpandCode(), "");
				this.initializeOther(userAccountInfo, "");
			}
		}
		bindOpenPlatformUserRelation(autoRegisterRequest.getOpenId(), autoRegisterRequest.getOpenPlatformId(), userAccountInfo.getId());
		return userAccountInfo;
	}
	
	/**
	 * 泰康用户注册
	 * 
	 * @param autoRegisterRequest
	 * @param userAccountInfo
	 */
	private UserAccountInfo registerTaiKangUser(UserAccountInfoAutoRegisterRequest autoRegisterRequest) {
		UserAccountInfo userAccountInfo = new UserAccountInfo();
		String accountName = createAccountName();
		userAccountInfo = insertUser(accountName, "", "", autoRegisterRequest.getApplicablePlatformId(), autoRegisterRequest.getExpandCode(), "");
		this.initializeOther(userAccountInfo, "");
		bindOpenPlatformUserRelation(autoRegisterRequest.getOpenId(), autoRegisterRequest.getOpenPlatformId(), userAccountInfo.getId());
		return userAccountInfo;
	}
	
	/**
	 * TCL用户注册
	 * 
	 * @param autoRegisterRequest
	 * @param userAccountInfo
	 */
	private UserAccountInfo registerTCLUser(UserAccountInfoAutoRegisterRequest autoRegisterRequest) throws Exception  {
		UserAccountInfo userAccountInfo = new UserAccountInfo();
		Map<String, Object> params = new HashMap<String, Object>();
		if (!StringUtil.isEmpty(autoRegisterRequest.getPhone())) {
			params.put("eqPhone", autoRegisterRequest.getPhone());
			params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
		} else {
			if (StringUtil.isEmpty(autoRegisterRequest.getEmail())) {
				throw new ServiceOperationException("TCL注册-手机号码和邮箱不能同时为空");
			}
			params.put("eqEmail", autoRegisterRequest.getEmail());
			params.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
		}
		PageList<UserAccountInfo> result = userAccountInfoDao.selectByMap(params, false);
		int count = result.size();
		String accountName = createAccountName();
		if(count == 0){
			userAccountInfo = insertUser(accountName, autoRegisterRequest.getEmail(), autoRegisterRequest.getPhone(), autoRegisterRequest.getApplicablePlatformId(), 
					autoRegisterRequest.getExpandCode(), "");
			this.initializeOther(userAccountInfo, "");
		} else{
			userAccountInfo = result.get(0);
			if (this.isBindOpenPlatformUser(userAccountInfo.getId(), autoRegisterRequest.getOpenPlatformId())) {
				userAccountInfo = insertUser(accountName, "", "", autoRegisterRequest.getApplicablePlatformId(), autoRegisterRequest.getExpandCode(), "");
				this.initializeOther(userAccountInfo, "");
			}
		}
		bindOpenPlatformUserRelation(autoRegisterRequest.getOpenId(), autoRegisterRequest.getOpenPlatformId(), userAccountInfo.getId());
		return userAccountInfo;
	}
	
	/**
	 * 平安用户注册
	 * 
	 * @param autoRegisterRequest
	 * @param userAccountInfo
	 */
	private UserAccountInfo registerPinganUser(UserAccountInfoAutoRegisterRequest autoRegisterRequest) {
		UserAccountInfo userAccountInfo = new UserAccountInfo();
		String accountName = createAccountName();
		userAccountInfo = insertUser(accountName, "", "", autoRegisterRequest.getApplicablePlatformId(), autoRegisterRequest.getExpandCode(), "");
		this.initializeOther(userAccountInfo, "");
		bindOpenPlatformUserRelation(autoRegisterRequest.getOpenId(), autoRegisterRequest.getOpenPlatformId(), userAccountInfo.getId());
		return userAccountInfo;
	}
	
	private Boolean isBindOpenPlatformUser(Integer userId, Integer openPlatformId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqUserId", userId);
		params.put("eqOpenPlatformId", openPlatformId);
		int count = userOpenPlatformInfoDao.selectCountByMap(params);
		if (count > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 微信商城或hdc注册
	 * 
	 * @param autoRegisterRequest
	 * @param userAccountInfo
	 */
	private UserAccountInfo registerWechatUser(UserAccountInfoAutoRegisterRequest autoRegisterRequest)  throws Exception {
		UserAccountInfo userAccountInfo = new UserAccountInfo();
		try {
			String openId = autoRegisterRequest.getOpenId();
			String phone = autoRegisterRequest.getPhone();
			Integer applicablePlatformId = autoRegisterRequest.getApplicablePlatformId();
			String expandCode = autoRegisterRequest.getExpandCode();
			Integer openPlatformId = autoRegisterRequest.getOpenPlatformId();
			
			if(StringUtil.isEmpty(phone)){
				String accountName = createAccountName();
				String passwd = ramdomPassword();
				userAccountInfo = insertUser(accountName, "", "", applicablePlatformId, expandCode, passwd);
				this.initializeOther(userAccountInfo, "");
			} else {
				// 手机号码
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("eqBingPhone", phone);
				params.put("eqWechatApplicationId", openPlatformId);
				int count = wechatUserBaseInfoDao.selectCountByMap(params);
				if (count > 0) {
					throw new ServiceOperationException("该手机号码已经绑定过微信用户");
				}
				params.clear();
				params.put("eqPhone", phone);
				params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
				PageList<UserAccountInfo> userAccountInfos = userAccountInfoDao.selectByMap(params, false);
				String messageContent = "";
				if (userAccountInfos != null && userAccountInfos.size() > 0) {
					userAccountInfo = userAccountInfos.get(0);
					int userId = userAccountInfo.getId();
					params.clear();
					params.put("eqUserId", userId);
					params.put("eqWechatApplicationId", openPlatformId);
					count = wechatUserBaseInfoDao.selectCountByMap(params);
					if (count > 0) {
						throw new ServiceOperationException("该账号已经绑定过微信用户");
					}
					messageContent = "尊敬的用户，您好！您的微信号已经绑定好药师官网账号，用户名：" + userAccountInfo.getAccountName() + "，好药师网站www.ehaoyao.com。";
				} else {
					String accountName = createAccountName();
					String passwd = ramdomPassword();
					userAccountInfo = insertUser(accountName, "", phone, applicablePlatformId, expandCode, passwd);
					this.initializeOther(userAccountInfo, "");
					messageContent = "尊敬的用户，您好！您的微信号已经绑定好药师官网账号，用户名：" + accountName + "，密码：" + passwd + "，好药师网站www.ehaoyao.com。";
				}
				//smsHelper.sendMessage(phone, messageContent, 8, SmsPartnerEnum.BAI_FEN.getCode());
				bindWechatPhone(openId, phone);
			}
			
			// 绑定官网用户和微信用户关系
			bindOpenPlatformUserRelation(openId, openPlatformId, userAccountInfo.getId());
			// 更新微信用户信息
			mergeWechatUser(openId, phone, userAccountInfo.getId(), userAccountInfo.getAccountName(), openPlatformId);
			
		} catch (Exception e) {
			throw new ServiceOperationException(e.getMessage());
		}
		return userAccountInfo;
	}
	
	/**
	 * 自动注册同步锁
	 * 
	 */
	private synchronized void autoRegisterAsync(UserAccountInfoAutoRegisterRequest autoRegisterRequest)  throws Exception {
		StringBuilder cacheKey = new StringBuilder();
		cacheKey.append(DataCacheKey.autoRegisterAsyncMapkey);
		if (!StringUtil.isEmpty(autoRegisterRequest.getOpenId())) {
			cacheKey.append("_").append(autoRegisterRequest.getOpenId());
		}
		if (!StringUtil.isEmpty(autoRegisterRequest.getPhone())) {
			cacheKey.append("_").append(autoRegisterRequest.getPhone());
		}
		if (!StringUtil.isEmpty(autoRegisterRequest.getEmail())) {
			cacheKey.append("_").append(autoRegisterRequest.getEmail());
		}
		if (autoRegisterRequest.getOpenPlatformId() > 0) {
			cacheKey.append("_").append(autoRegisterRequest.getOpenPlatformId());
		}
		if (autoRegisterRequest.getApplicablePlatformId() > 0) {
			cacheKey.append("_").append(autoRegisterRequest.getApplicablePlatformId());
		}
		do {
			if(null != cache.get(cacheKey.toString())) {
				log.info("func[autoRegisterAsync] 用户注册操作进程未完成，请求频率过频繁");
				throw new ServiceOperationException("该请求正在进行中，请稍等");
			} else {
				cache.put(cacheKey.toString(), 3, 3);
				return;
			}
		}while(true);
	}
	
	private void bindOpenPlatformUserRelation(String openId, Integer openPlatformId, Integer userId) {
		UserOpenPlatformInfo userOpenPlatformInfo = new UserOpenPlatformInfo();
		userOpenPlatformInfo.setOpenId(openId);
		userOpenPlatformInfo.setOpenPlatformId(openPlatformId);
		userOpenPlatformInfo.setUserId(userId);
		userOpenPlatformInfoDao.insert(userOpenPlatformInfo);
	}
	
	private void mergeWechatUser(String openId, String phone, Integer userId, String userName, Integer wechatApplicablePlatformId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqOpenId", openId);
		params.put("eqWechatApplicationId", wechatApplicablePlatformId);
		WechatUserBaseInfo wechatUserBaseInfo = new WechatUserBaseInfo();
		PageList<WechatUserBaseInfo> userBaseInfos = wechatUserBaseInfoDao.selectByMap(params, false);
		if (userBaseInfos != null && userBaseInfos.size() > 0) {
			wechatUserBaseInfo = userBaseInfos.get(0);
			wechatUserBaseInfo.setBingPhone(phone);
			wechatUserBaseInfo.setUserId(userId);
			wechatUserBaseInfo.setUserName(userName);
			wechatUserBaseInfo.setWechatApplicationId(wechatApplicablePlatformId);
			wechatUserBaseInfoDao.update(wechatUserBaseInfo);
		} else {
			wechatUserBaseInfo.setBingPhone(phone);
			wechatUserBaseInfo.setUserId(userId);
			wechatUserBaseInfo.setUserName(userName);
			wechatUserBaseInfo.setOpenId(openId);
			wechatUserBaseInfo.setWechatApplicationId(wechatApplicablePlatformId);
			wechatUserBaseInfoDao.insert(wechatUserBaseInfo);
		}
	}
	
	private void bindWechatPhone(String openId, String phone) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("eqOpenId", openId);
		param.put("eqPhone", phone);
		int count = wechatUserPhoneDao.selectCountByMap(param);
		if (count < 1) {
			WechatUserPhone wechatUserPhone = new WechatUserPhone();
			wechatUserPhone.setOpenId(openId);
			wechatUserPhone.setPhone(phone);
			wechatUserPhoneDao.insert(wechatUserPhone);
		}
	}
	
	/**
	 * 绑定微信用户手机号码
	 */
	@Override
	public Response bindWechatUserPhone(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			WechatUserPhoneBindRequest wechatUserPhoneBindRequest = (WechatUserPhoneBindRequest) request;
			Integer userId = wechatUserPhoneBindRequest.getUserId();
			String openId = wechatUserPhoneBindRequest.getOpenId();
			String phone = wechatUserPhoneBindRequest.getPhone();
			Integer wechatApplicationId = wechatUserPhoneBindRequest.getOpenPlatformId();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqUserId", userId);
			params.put("eqOpenId", openId);
			int count = userOpenPlatformInfoDao.selectCountByMap(params);
			if (count > 0) {
				params.clear();
				params.put("neOpenId", openId);
				params.put("eqBingPhone", phone);
				params.put("eqWechatApplicationId", wechatApplicationId);
				count = wechatUserBaseInfoDao.selectCountByMap(params);
				if (count > 0) {
					throw new ServiceOperationException("该手机号码已绑定过微信用户");
				}
				params.clear();
				params.put("eqUserId", userId);
				params.put("eqOpenId", openId);
				params.put("eqWechatApplicationId", wechatApplicationId);
				PageList<WechatUserBaseInfo> list = wechatUserBaseInfoDao.selectByMap(params, false);
				WechatUserBaseInfo wechatUserBaseInfo = list.get(0);
				wechatUserBaseInfo.setBingPhone(phone);
				wechatUserBaseInfoDao.update(wechatUserBaseInfo);
				this.bindWechatPhone(openId, phone);
			} else {
				throw new ServiceOperationException("该微信账号未绑定官网用户");
			}
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	@Override
	public Response unbindWechatUserPhone(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			WechatUserPhoneUnBindRequest userPhoneUnBindRequest = (WechatUserPhoneUnBindRequest) request;
			String openId = userPhoneUnBindRequest.getOpenId();
			String phone = userPhoneUnBindRequest.getPhone();
			Integer userId = userPhoneUnBindRequest.getUserId();
			Integer wechatApplicablePlatformId = userPhoneUnBindRequest.getOpenPlatformId();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqUserId", userId);
			params.put("eqOpenId", openId);
			int count = userOpenPlatformInfoDao.selectCountByMap(params);
			if (count > 0) {
				params.put("eqBingPhone", phone);
				params.put("eqWechatApplicationId", wechatApplicablePlatformId);
				count = wechatUserBaseInfoDao.selectCountByMap(params);
				if (count > 0) {
					//取消绑定微信用户，删除微信用户的相关信息
					deleteWechatUserInfo(openId, userId, wechatApplicablePlatformId);
				} else {
					throw new ServiceOperationException("该手机号码不是该用户的绑定手机号码");
				}
			} else {
				throw new ServiceOperationException("该微信账号未绑定官网用户");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	private void deleteWechatUserInfo(String openId, Integer userId, Integer wechatApplicablePlatformId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqOpenId", openId);
		wechatUserPhoneDao.deleteByMap(params);
		userOpenPlatformInfoDao.deleteByMap(params);
		
		params.put("eqUserId", userId);
		params.put("eqWechatApplicationId", wechatApplicablePlatformId);
		wechatUserBaseInfoDao.deleteByMap(params);
	}
	
	/**
	 * 随机生成6位密码
	 * 
	 * @return
	 */
	private String ramdomPassword() {
		int[] array = {0,1,2,3,4,5,6,7,8,9};
		Random rand = new Random();
		for (int i = 10; i > 1; i--) {
		    int index = rand.nextInt(i);
		    int tmp = array[index];
		    array[index] = array[i - 1];
		    array[i - 1] = tmp;
		}
		String result = "";
		for(int i = 0; i < 6; i++)
		    result = result + array[i];
		return String.valueOf(result);
	}
	
	/**
	 * 获取微信用户信息
	 */
	@Override
	public Response getWechatUserInfo(Request request)  throws Exception {
		ShowResponse<WechatUserBaseInfo> response = new ShowResponse<WechatUserBaseInfo>();
		try {
			WechatUserInfoRequest wechatUserInfoRequest = (WechatUserInfoRequest) request;
			Integer wechatApplicablePlatformId = wechatUserInfoRequest.getOpenPlatformId();
			String openId = wechatUserInfoRequest.getOpenId();
			String phone =  wechatUserInfoRequest.getPhone();
			Integer userId = wechatUserInfoRequest.getUserId();
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqWechatApplicationId", wechatApplicablePlatformId);
			
			if(!StringUtil.isEmpty(openId))
				params.put("eqOpenId", openId);
			
			if(!StringUtil.isEmpty(phone))
				params.put("eqBingPhone", phone);
			
			if(userId > 0) {
				params.put("eqUserId", userId);
			}

			PageList<WechatUserBaseInfo> list = wechatUserBaseInfoDao.selectByMap(params , 1 , 1, false);
			if(list.size() == 1){
				WechatUserBaseInfo wechatUserBaseInfo = list.get(0);
				response.setInfo(wechatUserBaseInfo);
			} else {
				throw new ServiceOperationException("该微信账号未绑定官网用户");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 更新已绑定微信用户的信息
	 */
	@Override
	public Response updateWechatUserInfo(Request request) throws Exception  {
		UpdateResponse<WechatUserBaseInfo> response = new UpdateResponse<WechatUserBaseInfo>();
		try {
			WechatUserInfoUpdateRequest wechatUserInfoUpdateRequest = (WechatUserInfoUpdateRequest) request;
			String openId = wechatUserInfoUpdateRequest.getOpenId();
			Integer userId = wechatUserInfoUpdateRequest.getUserId();
			Integer wechatPlatformId = wechatUserInfoUpdateRequest.getOpenPlatformId();
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("eqOpenId", openId);
			param.put("eqUserId", userId);
			param.put("eqOpenPlatformId", wechatPlatformId);
			int count = userOpenPlatformInfoDao.selectCountByMap(param);
			if (count > 0) {
				PageList<WechatUserBaseInfo> list = wechatUserBaseInfoDao.selectByMap(param, false);
				WechatUserBaseInfo wechatUserBaseInfo = list.get(0);
				if(StringUtil.isEmpty(wechatUserBaseInfo.getNickName())){
					updateFamilyBaseInfo(userId, wechatUserInfoUpdateRequest.getNickName());
				}
				wechatUserBaseInfo = updateWechatUserBaseInfo(wechatUserBaseInfo, wechatUserInfoUpdateRequest);
				response.setInfo(wechatUserBaseInfo);
			} else {
				throw new ServiceOperationException("该微信账号未绑定官网用户");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	private void updateFamilyBaseInfo(Integer userId ,String nickName){
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("eqUserId", userId);
		List<FamilyBaseInfo> list = familyBaseInfoDao.selectByMap(params, 1, 1, false);
		if(list.size() == 1){
			FamilyBaseInfo familyBaseInfo = list.get(0);
			if(StringUtil.isEmpty(familyBaseInfo.getName())){
				familyBaseInfo.setName(nickName + "的家");
				familyBaseInfoDao.update(familyBaseInfo);
			}
		}else{
			FamilyBaseInfo familyBaseInfo = new FamilyBaseInfo();
			familyBaseInfo.setName(nickName + "的家");
			familyBaseInfo.setUserId(userId);
			familyBaseInfoDao.insert(familyBaseInfo);
		}
	}
	
	private WechatUserBaseInfo updateWechatUserBaseInfo(WechatUserBaseInfo wechatUserBaseInfo, WechatUserInfoUpdateRequest wechatUserInfoUpdateRequest) {
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getAddrearea()))
			wechatUserBaseInfo.setAddrearea(UrlUtil.decode(wechatUserInfoUpdateRequest.getAddrearea()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getCity()))
			wechatUserBaseInfo.setCity(UrlUtil.decode(wechatUserInfoUpdateRequest.getCity()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getCountry()))
			wechatUserBaseInfo.setCountry(UrlUtil.decode(wechatUserInfoUpdateRequest.getCountry()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getCreateTime()))
			wechatUserBaseInfo.setCreateTime(wechatUserInfoUpdateRequest.getCreateTime());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getHeadImgUrl()))
			wechatUserBaseInfo.setHeadImgUrl(wechatUserInfoUpdateRequest.getHeadImgUrl());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getLanguage()))
			wechatUserBaseInfo.setLanguage(wechatUserInfoUpdateRequest.getLanguage());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getNickName()))
			wechatUserBaseInfo.setNickName(UrlUtil.decode(wechatUserInfoUpdateRequest.getNickName()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getOpenId()))
			wechatUserBaseInfo.setOpenId(wechatUserInfoUpdateRequest.getOpenId());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getProvince()))
			wechatUserBaseInfo.setProvince(UrlUtil.decode(wechatUserInfoUpdateRequest.getProvince()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getReceiveArea()))
			wechatUserBaseInfo.setReceiveArea(UrlUtil.decode(wechatUserInfoUpdateRequest.getReceiveArea()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getReceiveCity()))
			wechatUserBaseInfo.setReceiveCity(UrlUtil.decode(wechatUserInfoUpdateRequest.getReceiveCity()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getReceiveDetailInfo()))
			wechatUserBaseInfo.setReceiveDetailInfo(UrlUtil.decode(wechatUserInfoUpdateRequest.getReceiveDetailInfo()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getReceiveProvince()))
			wechatUserBaseInfo.setReceiveProvince(UrlUtil.decode(wechatUserInfoUpdateRequest.getReceiveProvince()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getReceiver()))
			wechatUserBaseInfo.setReceiver(UrlUtil.decode(wechatUserInfoUpdateRequest.getReceiver()));
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getReceiveZipcode()))
			wechatUserBaseInfo.setReceiveZipcode(wechatUserInfoUpdateRequest.getReceiveZipcode());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getSex()))
			wechatUserBaseInfo.setSex(wechatUserInfoUpdateRequest.getSex());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getReceiveTel()))
			wechatUserBaseInfo.setReceiveTel(wechatUserInfoUpdateRequest.getReceiveTel());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getSubScribe()))
			wechatUserBaseInfo.setSubScribe(wechatUserInfoUpdateRequest.getSubScribe());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getSubscribeTime()))
			wechatUserBaseInfo.setSubscribeTime(wechatUserInfoUpdateRequest.getSubscribeTime());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getUnsubscribeTime()))
			wechatUserBaseInfo.setUnsubscribeTime(wechatUserInfoUpdateRequest.getUnsubscribeTime());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getUpdateTime()))
			wechatUserBaseInfo.setUpdateTime(wechatUserInfoUpdateRequest.getUpdateTime());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getUyuyUserid()))
			wechatUserBaseInfo.setUyuyUserid(wechatUserInfoUpdateRequest.getUyuyUserid());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getX()))
			wechatUserBaseInfo.setX(wechatUserInfoUpdateRequest.getX());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getY()))
			wechatUserBaseInfo.setY(wechatUserInfoUpdateRequest.getY());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getWxuserid()))
			wechatUserBaseInfo.setWxuserId(wechatUserInfoUpdateRequest.getWxuserid());
		if (!StringUtil.isEmpty(wechatUserInfoUpdateRequest.getUnionid())) {
			wechatUserBaseInfo.setUnionId(wechatUserInfoUpdateRequest.getUnionid());
		}
		wechatUserBaseInfoDao.update(wechatUserBaseInfo);
		return wechatUserBaseInfo;
	}
	
	/**
	 * 验证用户名
	 */
	@Override
	public Response verifyName(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserVerifyNameRequest userVerifyRequest = (UserVerifyNameRequest) request;
			String accountName = userVerifyRequest.getAccountName();
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("eqAccountName", accountName);
			int count = userAccountInfoDao.selectCountByMap(param);
			if (count > 0) {
				throw new ServiceOperationException("用户名已存在");
			}
			response.setTip("该用户名可用");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 验证邮箱
	 */
	@Override
	public Response verifyEmail(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserVerifyEmailRequest userVerifyEmailRequest = (UserVerifyEmailRequest) request;
			String email = userVerifyEmailRequest.getEmail();
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("eqEmail", email);
			param.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			int count = userAccountInfoDao.selectCountByMap(param);
			if (count > 0) {
				throw new ServiceOperationException("该邮箱已存在");
			}
			response.setTip("该邮箱可用");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 验证手机号码
	 */
	@Override
	public Response verifyPhone(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserVerifyPhoneRequest userVerifyPhoneRequest = (UserVerifyPhoneRequest) request;
			String phone = userVerifyPhoneRequest.getPhone();
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("eqPhone", phone);
			param.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			int count = userAccountInfoDao.selectCountByMap(param);
			if (count > 0) {
				throw new ServiceOperationException("该手机号码已存在");
			}
			response.setTip("该手机可用");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 登录
	 * verify = 用户id+用户名+expires过期时间+ip地址+key
	 */
	@Override
	public Response login(Request request)  throws Exception {
		UserLoginResponse response = new UserLoginResponse();
		UserLoginRequest loginRequest = (UserLoginRequest) request;
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			String userName = loginRequest.getUsername();
			String password = loginRequest.getPassword();
			String ip = loginRequest.getIp();
			String pw = StringUtil.md5(password);
			verifyParams(userName, params);
			params.put("eqPasswd", pw);
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(params, false);
			if (list != null && list.size() > 0) {
				UserAccountInfo userAccountInfo = list.get(0);
				UserBaseAccountInfo userBaseAccountInfo = creatVerify(userAccountInfo, ip);
				response.setUserBaseAccountInfo(userBaseAccountInfo);
			} else {
				throw new ServiceOperationException("登录失败");
			}
		} catch (Exception e) {
			loginRequest.setPassword("******");
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	private UserBaseAccountInfo creatVerify(UserAccountInfo userAccountInfo, String ip) { 
		int userId = userAccountInfo.getId();
		UserBaseAccountInfo userBaseAccountInfo = userAccountInfoDao.selectByUserId(userId);

		String verify = userId +"|"+ UrlUtil.encode(userBaseAccountInfo.getAccountName(),"utf8")
													+"|" + PrivateKey.HAOYAO_PRIVATE_KEY.getValue();
		// 记录服务端请求的登录状态
		cache.put(DataCacheKey.verifyMapKey + String.valueOf(userId) , StringUtil.base64Encode(verify) , cacheLifeCycle);
		// cookie的verify用md5
		userBaseAccountInfo.setVerify(StringUtil.md5(verify));
		return userBaseAccountInfo;
	}
	
	/**
	 * 判断该账户是否有绑定手机号
	 */
	@Override
	public Response isBindPhoneByUsername(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			UserVerifyBindPhoneRequest userVerifyBindPhoneRequest = (UserVerifyBindPhoneRequest) request;
			String username = userVerifyBindPhoneRequest.getUsername();
			Map<String, Object> params = new HashMap<String, Object>();
			verifyParams(username, params);
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(params, false);
			if (list != null && list.size() > 0) {
				UserAccountInfo userAccountInfo = list.get(0);
				if (userAccountInfo.getIsPhoneValid() == UserAccountInfoStatusEnum.AVAILABILITY_NO.getId()) {
					throw new ServiceOperationException("该用户未绑定手机号码");
				}
			} else {
				throw new ServiceOperationException("该账号不存在");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 手机动态密码登录
	 */
	@Override
	public Response loginByDynamicPassword(Request request) throws Exception  {
		UserLoginResponse response = new UserLoginResponse();
		try {
			UserLoginByDynamicPasswordRequest loginByDynamicPasswordRequest = (UserLoginByDynamicPasswordRequest) request;
			String username = loginByDynamicPasswordRequest.getUsername();
			String dynamicPassword = loginByDynamicPasswordRequest.getDynamicPassword();
			String ip = loginByDynamicPasswordRequest.getIp();
			Integer applicablePlatformId = loginByDynamicPasswordRequest.getApplicablePlatformId();
			Map<String, Object> params = new HashMap<String, Object>();
			verifyParams(username, params);
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(params, false);
			String phone = "";
			UserAccountInfo userAccountInfo = new UserAccountInfo();
			if (list.size() > 0) {
				userAccountInfo = list.get(0);
				phone = userAccountInfo.getPhone();
			} else {
				if (StringUtil.isMobilePhone(username)) {
					phone = username;
				} else {
					throw new ServiceOperationException("该账号不存在");
				}
			}
			Response result = smsHelper.checkVerify(phone, dynamicPassword, UserMessageSmsVerifyCode.SendOperationEnum.LOGIN.getValue(), applicablePlatformId, UserMessageStatusEnum.VERIFY.getId());
			if (result.getCode() == ApiResultEnum.SUCCESS.getId()) {
				if (list.size() < 1) {
					this.registerByDynamicPWAsync(username, applicablePlatformId);
					// 如果是手机号码 并未注册的，自动进行注册
					String substr = username.substring(username.length() - 4, username.length());
					String nickname = creatAccountNameByPhone(substr);
					userAccountInfo = this.insertUser(nickname, "", username, applicablePlatformId, loginByDynamicPasswordRequest.getExpandCode(), "");
					initializeOther(userAccountInfo, nickname);
				}
			} else {
				throw new ServiceOperationException(result.getTip());
			}
			UserBaseAccountInfo userBaseAccountInfo = creatVerify(userAccountInfo, ip);
			response.setUserBaseAccountInfo(userBaseAccountInfo);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 动态密码注册同步锁
	 * 
	 * @param phone
	 * @param applicablePlatformId
	 */
	private synchronized void registerByDynamicPWAsync(String phone, Integer applicablePlatformId) throws Exception  {
		String cacheKey = DataCacheKey.registerByDyPwAsyncMapkey + phone + "_" + applicablePlatformId; 
		do {
			if(null != cache.get(cacheKey)) {
				log.info("func[registerByDynamicPWAsync] 用户注册操作进程未完成，请求频率过频繁");
				throw new ServiceOperationException("该请求正在进行中，请稍等");
			} else {
				cache.put(cacheKey, 3, 100);
				return;
			}
		}while(true);
	}
	
	/**
	 * 发送手机动态密码
	 */
	@Override
	public Response sendDynamicPaswordByUsername(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			SmsSendDynamicPasswordRequest dynamicPasswordRequest = (SmsSendDynamicPasswordRequest) request;
			String username = dynamicPasswordRequest.getUsername();
			Integer applicablePlatformId = dynamicPasswordRequest.getApplicablePlatformId();
			Map<String, Object> params = new HashMap<String, Object>();
			verifyParams(username, params);
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(params, false);
			if (list != null && list.size() > 0) {
				UserAccountInfo userAccountInfo = list.get(0);
				if (userAccountInfo.getIsPhoneValid() == UserAccountInfoStatusEnum.AVAILABILITY_YES.getId()) {
					String phone = userAccountInfo.getPhone();
					smsHelper.sendVerify(phone, UserMessageSmsVerifyCode.SendOperationEnum.LOGIN.getValue(), 120, 
							applicablePlatformId, SmsPartnerEnum.BAI_FEN.getCode());
				} else {
					throw new ServiceOperationException("该账号未绑定手机号码");
				}
			} else {
				if (StringUtil.isMobilePhone(username)) {
					smsHelper.sendVerify(username, UserMessageSmsVerifyCode.SendOperationEnum.LOGIN.getValue(), 120, 
							applicablePlatformId, SmsPartnerEnum.BAI_FEN.getCode());
				} else {
					throw new ServiceOperationException("该账号不存在");
				}
			}
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 免密码登录
	 */
	@Override
	public Response loginNoPassword(Request request) throws Exception  {
		UserLoginResponse response = new UserLoginResponse();
		try {
			UserLoginNoPasswordRequest loginNoPasswordRequest = (UserLoginNoPasswordRequest) request;
			String userName = loginNoPasswordRequest.getUsername();
			String ip = loginNoPasswordRequest.getIp();
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqAccountName", userName);
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(params, false);
			if (list != null && list.size() > 0) {
				UserAccountInfo userAccountInfo = list.get(0);
				UserBaseAccountInfo userBaseAccountInfo = creatVerify(userAccountInfo, ip);
				response.setUserBaseAccountInfo(userBaseAccountInfo);
			} else {
				throw new ServiceOperationException("登录失败");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 用户退出
	 */
	@Override
	public Response logout(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			UserLogoutRequest userLogoutRequest = (UserLogoutRequest) request;
			int userId = userLogoutRequest.getUserId();
			UserAccountInfo userAccountInfo = userAccountInfoDao.selectById(userId);
			if (userAccountInfo == null) {
				throw new ServiceOperationException("该用户不存在");
			}
			cache.remove(DataCacheKey.verifyMapKey + userId);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 验证用户是否登录
	 * 因为在拦截器中 {@link VerifyInterceptor} 已经做了验证 所以此处不用再做验证
	 */
	@Override
	public Response isLogin(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			UserVerifyRequest verifyRequest = (UserVerifyRequest) request;
			Integer userId = verifyRequest.getUserId();
			String verify = verifyRequest.getVerify();
			String ip = verifyRequest.getIp();
			
			verify(verify, userId, ip);
			response.setTip("验证通过");
		} catch(Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("验证不通过：" + e.getMessage());
		}
		
		return response;
	}
	
	/**
	 * 验证登录加密串
	 * @param verifyCode
	 * @param userId
	 * @param ip
	 */
	@Override
	public void verify(String verifyCode,Integer userId,String ip) throws Exception {
		
		String cacheVerifyCode = (String)cache.get(DataCacheKey.verifyMapKey + String.valueOf(userId));
		if (StringUtil.isEmpty(cacheVerifyCode)) {
			throw new ServiceOperationException("该用户未登录");
		} else if (!verifyCode.equals(StringUtil.md5(StringUtil.base64Decode(cacheVerifyCode)))) {
			throw new ServiceOperationException("该用户登录失效");
		}

		String cacheVerifyCodeDecode = StringUtil.base64Decode(cacheVerifyCode);
		String[] cacheVerifyCodeDecodeArray = cacheVerifyCodeDecode.split("\\|");
		
		if(userId != Integer.parseInt(cacheVerifyCodeDecodeArray[0])){
			throw new ServiceOperationException("用户id验证有误");
		}

		//每次验证通过后，刷新验证串的时效
		cache.put(DataCacheKey.verifyMapKey + String.valueOf(userId), cacheVerifyCode, cacheLifeCycle);
	}
	
	/**
	 * 获取用户详细信息
	 */
	@Override
	public Response getUser(Request request)  throws Exception {
		UserAccountDetailResponse response = new UserAccountDetailResponse();
		try {
			UserAccountDetailRequest userAccountDetailRequest = (UserAccountDetailRequest) request;
			int userId = userAccountDetailRequest.getUserId();
			UserBaseAccountInfo userBaseAccountInfo = userAccountInfoDao.selectByUserId(userId);
			if (userBaseAccountInfo != null) {
				if(UserAccountInfoStatusEnum.AVAILABILITY_YES.getId() != userBaseAccountInfo.getIsPhoneValid()) {
					userBaseAccountInfo.setPhone("");
				}
				if(UserAccountInfoStatusEnum.AVAILABILITY_YES.getId() != userBaseAccountInfo.getIsEmailValid()) {
					userBaseAccountInfo.setEmail("");
				}
				response.setUserBaseAccountInfo(userBaseAccountInfo);
			} else {
				throw new ServiceOperationException("用户不存在");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	/**
	 * 获取用户详细信息（泰康）
	 */
	@Override
	public Response getUserByTaikang(Request request)  throws Exception {
		ShowResponse<TaiKangUserInfo> response = new ShowResponse<TaiKangUserInfo>();
		try {
			UserAccountDetailRequest userAccountDetailRequest = (UserAccountDetailRequest) request;
			int userId = userAccountDetailRequest.getUserId();
			UserBaseAccountInfo userBaseAccountInfo = userAccountInfoDao.selectByUserId(userId);
			TaiKangUserInfo taiKangUserInfo = new TaiKangUserInfo();
			if (userBaseAccountInfo != null) {
				if(UserAccountInfoStatusEnum.AVAILABILITY_YES.getId() != userBaseAccountInfo.getIsPhoneValid()) {
					userBaseAccountInfo.setPhone("");
				}
				if(UserAccountInfoStatusEnum.AVAILABILITY_YES.getId() != userBaseAccountInfo.getIsEmailValid()) {
					userBaseAccountInfo.setEmail("");
				}
				this.setTaikangUser(taiKangUserInfo, userBaseAccountInfo);
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("eqUserId", userId);
				params.put("eqOpenPlatformId", OpenPlatformEnum.TAIKANG.getId());
				PageList<UserOpenPlatformInfo> list = userOpenPlatformInfoDao.selectByMap(params, false);
				if (list.size() > 0) {
					UserOpenPlatformInfo openPlatformInfo = list.get(0);
					taiKangUserInfo.setOpenId(openPlatformInfo.getOpenId());
				}
				response.setInfo(taiKangUserInfo);
			} else {
				throw new ServiceOperationException("用户不存在");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	private void setTaikangUser(TaiKangUserInfo kangUserInfo, UserBaseAccountInfo userBaseAccountInfo) {
		kangUserInfo.setId(userBaseAccountInfo.getId());
		kangUserInfo.setAccountName(userBaseAccountInfo.getAccountName());
		kangUserInfo.setAge(userBaseAccountInfo.getAge());
		kangUserInfo.setBirthday(userBaseAccountInfo.getBirthday());
		kangUserInfo.setCreateTime(userBaseAccountInfo.getCreateTime());
		kangUserInfo.setDefaultAddress(userBaseAccountInfo.getDefaultAddress());
		kangUserInfo.setDefaultContactWay(userBaseAccountInfo.getDefaultContactWay());
		kangUserInfo.setDefaultPhone(userBaseAccountInfo.getDefaultPhone());
		kangUserInfo.setEmail(userBaseAccountInfo.getEmail());
		kangUserInfo.setHeadImageUrl(userBaseAccountInfo.getHeadImageUrl());
		kangUserInfo.setIdentityCard(userBaseAccountInfo.getIdentityCard());
		kangUserInfo.setIdentityType(userBaseAccountInfo.getIdentityType());
		kangUserInfo.setIsEmailValid(userBaseAccountInfo.getIsEmailValid());
		kangUserInfo.setIsPhoneValid(userBaseAccountInfo.getIsPhoneValid());
		kangUserInfo.setNickName(userBaseAccountInfo.getNickName());
		kangUserInfo.setPhone(userBaseAccountInfo.getPhone());
		kangUserInfo.setRealName(userBaseAccountInfo.getRealName());
		kangUserInfo.setSex(userBaseAccountInfo.getSex());
		kangUserInfo.setTags(userBaseAccountInfo.getTags());
		kangUserInfo.setUserType(userBaseAccountInfo.getUserType());
		kangUserInfo.setVerify("");
	}
	
	/**
	 * 账号更新
	 */
	@Override
	public Response update(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserAccountInfoUpdateRequest accountInfoUpdateRequest = (UserAccountInfoUpdateRequest) request;
			int userId = accountInfoUpdateRequest.getUserId();
			String email = accountInfoUpdateRequest.getEmail();
			String phone = accountInfoUpdateRequest.getPhone();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			params.put("email", email);
			params.put("phone", phone);
			int count = userAccountInfoDao.updateByMap(params);
			if (count < 1) {
				throw new ServiceOperationException("更新失败");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 忘记密码账号验证
	 */
	@Override
	public Response lostpasswordByAccount(Request request)  throws Exception {
		UserLostpassByAccountResponse response = new UserLostpassByAccountResponse();
		try {
			UserLostpasswordByAccountRequest userLostpasswordByAccountRequest = (UserLostpasswordByAccountRequest) request;
			String accountName = userLostpasswordByAccountRequest.getAccountName();
			String email = userLostpasswordByAccountRequest.getEmail();
			String phone = userLostpasswordByAccountRequest.getPhone();
			Map<String, Object> params = new HashMap<String, Object>();
			if (!StringUtil.isEmpty(accountName)) {
				params.put("eqAccountName", accountName);
			}
			if (!StringUtil.isEmpty(email)) {
				params.put("eqEmail", email);
				params.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			}
			if (!StringUtil.isEmpty(phone)) {
				params.put("eqPhone", phone);
				params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			}
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(params, false);
			if (list != null && list.size() > 0) {
				UserAccountInfo userAccountInfo = list.get(0);
				if (!StringUtil.isEmpty(email) && userAccountInfo.getIsEmailValid() == UserAccountInfoStatusEnum.AVAILABILITY_NO.getId()) {
					throw new ServiceOperationException("该用户未绑定邮箱");
				}
				if (!StringUtil.isEmpty(phone) && userAccountInfo.getIsPhoneValid() == UserAccountInfoStatusEnum.AVAILABILITY_NO.getId()) {
					throw new ServiceOperationException("该用户未绑定手机号码");
				}
				response.setAccountName(userAccountInfo.getAccountName());
				response.setIsEmailValid(userAccountInfo.getIsEmailValid());
				if (userAccountInfo.getIsEmailValid() == UserAccountInfoStatusEnum.AVAILABILITY_YES.getId()) {
					response.setEmail(userAccountInfo.getEmail());
				}
				response.setIsPhoneValid(userAccountInfo.getIsPhoneValid());
				if (userAccountInfo.getIsPhoneValid() == UserAccountInfoStatusEnum.AVAILABILITY_YES.getId()) {
					response.setPhone(userAccountInfo.getPhone());
				}
				response.setUserId(userAccountInfo.getId());
				//cache.put(DataCacheKey.findPasswordCodeMapKey + userAccountInfo.getId(), StringUtil.md5(userAccountInfo.getId().toString()), 60*30);
			} else {
				throw new ServiceOperationException("用户不存在");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 发送找回密码验证的邮箱
	 */
	@Override
	public Response sendEmailByLostpassword(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserLostpasswordByEmailRequest emailRequest = (UserLostpasswordByEmailRequest) request;
			Integer userId = emailRequest.getUserId();
			String email = emailRequest.getEmail();
//			String key = emailRequest.getKey();
//			if (!key.equals(cache.get(DataCacheKey.findPasswordCodeMapKey + userId))) {
//				throw new ServiceOperationException("key已失效");
//			}
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			params.put("eqEmail", email);
			params.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(params, false);
			UserAccountInfo userAccountInfo = new UserAccountInfo();
			if (list != null && list.size() > 0) {
				userAccountInfo = list.get(0);
			} else {
				throw new ServiceOperationException("用户不存在");
			}
			// 发送找回密码邮箱验证串
			Map<String,Object> content = new HashMap<String,Object>();
			String emailKey = StringUtil.md5(userId + email + new Date());
			cache.put(DataCacheKey.emailPasswordCheckCodeMapKey + userId, emailKey, 60 * 30);
			
			String url = WebSiteEnum.HTTP_UCENTER+"/user/resetPwBykey?ui="+UrlUtil.encode(StringUtil.base64Encode(userId.toString())) + "&k=" + emailKey;
			String accountName = userAccountInfo.getAccountName();
			content.put(MailingEnum.RESET_PSW_URL.getParamName(), url);
			content.put(MailingEnum.ACCOUNT.getParamName(), accountName);
//			mailingHelper.addMailReciever(email, content);
//			mailingHelper.sendFindPswEmail(email);
			
//			content.put("url", WebSiteEnum.HTTP_UCENTER+"/user/resetPwBykey?ui="+UrlUtil.encode(StringUtil.base64Encode(userId.toString())) + "&k=" + emailKey);
//			content.put("username", userAccountInfo.getAccountName());
//			String nameOfTo = MimeUtility.encodeText(userAccountInfo.getAccountName(), "utf-8", "B");
//	        String to = nameOfTo + "<" + email + ">";
//	        velocityMailSupportHelper.setDefaultEncoding("GBK");
//	        velocityMailSupportHelper.setSubject("找回密码");
//	        velocityMailSupportHelper.setTemplateName("reset_password_mail.vm");
//
//            SimpleMailMessage simpleMessage = velocityMailSupportHelper.mergeSimpleMessage(to, content);
//            MimeMessage mimeMessage = velocityMailSupportHelper.toMimeMessage(simpleMessage);
//
//            mimeMessage.setHeader("Content-Type", "text/html; charset=utf-8");
//            mimeMessage.setFrom(new InternetAddress("gz_development@163.com", "好药师商城"));
//            velocityMailSupportHelper.getJavaMailSender().send(mimeMessage);
            
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 更新邮箱认证状态
	 */
	@Override
	public Response updateEmailValid(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
//			cache.put("email_checkCode","670131320");
			UserAccountEmailUpdateRequest userAccountEmailUpdateRequest = (UserAccountEmailUpdateRequest) request;
			int userId = userAccountEmailUpdateRequest.getUserId();
			String email = userAccountEmailUpdateRequest.getEmail();
			String code = userAccountEmailUpdateRequest.getCode();
			String checkCode = (String) cache.get(DataCacheKey.emailCheckCodeMapKey + userId);//验证码，注册成功时插入缓存的
			if(null!=checkCode && !"".equals(checkCode)){
				if(null!=code && checkCode.equals(code)){
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("isEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
					params.put("eqEmail", email);
					int count = userAccountInfoDao.updateByMap(params);
					if (count < 1) {
						throw new ServiceOperationException("更新失败");
					}
					response.setTip("更新成功");
				}else{
					throw new ServiceOperationException("验证码不正确");
				}
			}else{
				throw new ServiceOperationException("验证码已过期");
			}
			cache.remove(DataCacheKey.emailCheckCodeMapKey + userId);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	@Override
	public Response resetPasswd(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		UserResetPasswordRequest userResetPasswordRequest = (UserResetPasswordRequest) request;
		try {
			Integer userId = userResetPasswordRequest.getUserId();
			String key = userResetPasswordRequest.getKey();
			String passwd = userResetPasswordRequest.getPasswd();
			if (!key.equals(cache.get(DataCacheKey.emailPasswordCheckCodeMapKey + userId))) {
				throw new ServiceOperationException("已失效");
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("eqId", userId);
			param.put("passwd", StringUtil.md5(passwd));
			int count = userAccountInfoDao.updateByMap(param);
			if (count < 1) {
				throw new ServiceOperationException("重置密码失败");
			} else {
				UserPasswordModifyLog object = new UserPasswordModifyLog();
				object.setConfirmIp(userResetPasswordRequest.getIp());
				object.setConfirmWay(ModifyWayEnum.EMAIL.getType());
				object.setUserId(userId);
				passwordLogDao.insert(object);
			}
			cache.remove(DataCacheKey.emailPasswordCheckCodeMapKey + userId);
		} catch (Exception e) {
			userResetPasswordRequest.setConfirmPasswd("******");
			userResetPasswordRequest.setPasswd("******");
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 根据手机号重置密码
	 */
	@Override
	public Response resetPasswdByPhone(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		UserResetPasswordByPhoneRequest userResetPasswordByPhoneRequest = (UserResetPasswordByPhoneRequest) request;
		try {
			Integer userId = userResetPasswordByPhoneRequest.getUserId();
			String key = userResetPasswordByPhoneRequest.getKey();
			String phone =userResetPasswordByPhoneRequest.getPhone();
			String passwd = userResetPasswordByPhoneRequest.getPasswd();
			Response smsResponse = smsHelper.checkVerify(phone, key, UserMessageSmsVerifyCode.SendOperationEnum.FIND_PASSWORD.getValue(), ApplicablePlatformEnum.WEB.getId(), UserMessageStatusEnum.VERIFY.getId());
			if (smsResponse.getCode() == ApiResultEnum.SUCCESS.getId()) {
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("eqId", userId);
				param.put("eqPhone", phone);
				param.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
				param.put("passwd", StringUtil.md5(passwd));
				int count = userAccountInfoDao.updateByMap(param);
				if (count < 1) {
					throw new ServiceOperationException("重置密码失败");
				} else {
					//修改记录
					UserPasswordModifyLog object = new UserPasswordModifyLog();
					object.setConfirmIp(userResetPasswordByPhoneRequest.getIp());
					object.setConfirmWay(ModifyWayEnum.PHONE.getType());
					object.setUserId(userId);
					passwordLogDao.insert(object);
				}
			} else {
				throw new ServiceOperationException("验证码错误");
			}
		} catch (Exception e) {
			userResetPasswordByPhoneRequest.setConfirmPasswd("******");
			userResetPasswordByPhoneRequest.setPasswd("******");
			log.error("func[resetPasswdByPhone] request[" + userResetPasswordByPhoneRequest + "] error[" + e.getMessage() + "]", e);
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 更新密码
	 */
	@Override
	public Response updatePasswd(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		UserPasswordUpdateRequest passwordUpdateRequest = (UserPasswordUpdateRequest) request;
		try {
			Integer userId = passwordUpdateRequest.getUserId();
			String oldPasswd = passwordUpdateRequest.getOldPasswd();
			String passwd = passwordUpdateRequest.getPasswd();
			UserAccountInfo accountInfo = userAccountInfoDao.selectById(userId);
			if (accountInfo == null) {
				throw new ServiceOperationException("不存在该用户");
			}
			if (!StringUtil.md5(oldPasswd).equals(accountInfo.getPasswd())) {
				throw new ServiceOperationException("旧密码错误");
			}
			if (oldPasswd.equals(passwd)) {
				throw new ServiceOperationException("新旧密码一样");
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("eqId", userId);
			param.put("passwd", StringUtil.md5(passwd));
			int count = userAccountInfoDao.updateByMap(param);
			if (count < 1) {
				throw new ServiceOperationException("更新失败");
			} else {
				//修改记录
				UserPasswordModifyLog object = new UserPasswordModifyLog();
				object.setConfirmIp(passwordUpdateRequest.getIp());
				object.setConfirmWay(ModifyWayEnum.COMMON.getType());
				object.setUserId(userId);
				passwordLogDao.insert(object);
			}
			response.setTip("密码更新成功");
		} catch (Exception e) {
			passwordUpdateRequest.setConfirmPasswd("******");
			passwordUpdateRequest.setOldPasswd("******");
			passwordUpdateRequest.setPasswd("******");
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 绑定账号邮箱
	 */
	@Override
	public Response bindEmail(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			UserBindEmailRequest userBindEmailRequest = (UserBindEmailRequest) request;
			Integer userId = userBindEmailRequest.getUserId();
			String email = userBindEmailRequest.getEmail();
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			int count = userAccountInfoDao.selectCountByMap(params);
			if (count < 1) {
				throw new ServiceOperationException("该用户不存在");	
			}
			params.put("eqEmail", email);
			params.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			if (userAccountInfoDao.selectCountByMap(params) > 0) {
				throw new ServiceOperationException("该用户已绑定过这个邮箱");
			}
			params.clear();
			params.put("eqEmail", email);
			params.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			if (userAccountInfoDao.selectCountByMap(params) > 0) {
				throw new ServiceOperationException("该邮箱已经被绑定过");
			}
			params.clear();
			params.put("eqId", userId);
			params.put("email", email);
			params.put("isEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			userAccountInfoDao.updateByMap(params);
			
			//RecordResultType record = mailingHelper.addMailReciever(email,null);
			//添加用户邮箱
			/*if(null != record && !RecordResultTypeStatus._ERROR.equalsIgnoreCase(record.getStatus().getValue())) {
				//添加成功发送欢迎邮件
				mailingHelper.sendWelcomeMail(email);
			}*/
			response.setTip("成功绑定该邮箱");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 解绑账号邮箱
	 */
	@Override
	public Response unbindEmail(Request request)  throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserUnbindEmailRequest userUnbindEmailRequest = (UserUnbindEmailRequest) request;
			Integer userId = userUnbindEmailRequest.getUserId();
			String email = userUnbindEmailRequest.getEmail();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			int count = userAccountInfoDao.selectCountByMap(params);
			if (count < 1) {
				throw new ServiceOperationException("该用户不存在");	
			}
			params.put("eqEmail", email);
			params.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			if (userAccountInfoDao.selectCountByMap(params) < 1) {
				throw new ServiceOperationException("该用户未绑定此邮箱：" + email);
			}
			params.clear();
			params.put("eqId", userId);
			params.put("isEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_NO.getId());
			userAccountInfoDao.updateByMap(params);
			response.setTip("成功解绑该邮箱");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 绑定账号手机号码
	 */
	@Override
	public Response bindPhone(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			UserBindPhoneRequest userBindPhoneRequest = (UserBindPhoneRequest) request;
			Integer userId = userBindPhoneRequest.getUserId();
			String phone = userBindPhoneRequest.getPhone();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			int count = userAccountInfoDao.selectCountByMap(params);
			if (count < 1) {
				throw new ServiceOperationException("该用户不存在");	
			}
			params.put("eqPhone", phone);
			params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			if (userAccountInfoDao.selectCountByMap(params) > 0) {
				throw new ServiceOperationException("该用户已绑定过这个手机号码");
			}
			params.clear();
			params.put("eqPhone", phone);
			params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			if (userAccountInfoDao.selectCountByMap(params) > 0) {
				throw new ServiceOperationException("该手机号码已经被绑定过");
			}
			params.clear();
			params.put("eqId", userId);
			params.put("phone", phone);
			params.put("isPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			userAccountInfoDao.updateByMap(params);
			response.setTip("成功绑定该手机号码");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	@Override
	public Response unbindPhone(Request request) throws Exception {
		DefaultResponse response = new DefaultResponse();
		try {
			UserUnbindPhoneRequest userUnbindPhoneRequest = (UserUnbindPhoneRequest) request;
			Integer userId = userUnbindPhoneRequest.getUserId();
			String phone = userUnbindPhoneRequest.getPhone();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			int count = userAccountInfoDao.selectCountByMap(params);
			if (count < 1) {
				throw new ServiceOperationException("该用户不存在");	
			}
			params.put("eqPhone", phone);
			params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			if (userAccountInfoDao.selectCountByMap(params) < 1) {
				throw new ServiceOperationException("该用户未绑定此手机号码：" + phone);
			}
			params.clear();
			params.put("eqId", userId);
			//params.put(key, value)
			params.put("isPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_NO.getId());
			userAccountInfoDao.updateByMap(params);
			response.setTip("成功解绑该手机号码");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	@Override
	public Response verifyWechatPhone(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			WechatUserVerifyPhoneRequest verifyPhoneRequest = (WechatUserVerifyPhoneRequest) request;
			String openId = verifyPhoneRequest.getOpenId();
			String phone = verifyPhoneRequest.getPhone();
			Integer wechatApplicationId = verifyPhoneRequest.getOpenPlatformId();
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("neOpenId", openId);
			param.put("eqBingPhone", phone);
			param.put("eqWechatApplicationId", wechatApplicationId);
			int count = wechatUserBaseInfoDao.selectCountByMap(param);
			if (count > 0) {
				throw new ServiceOperationException("该手机号码已经被绑定过");
			}
			param.clear();
			param.put("eqPhone", phone);
			param.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(param, false);
			if (list != null && list.size() > 0) {
				UserAccountInfo userAccountInfo = list.get(0);
				Integer userId = userAccountInfo.getId();
				param.clear();
				param.put("neOpenId", openId);
				param.put("eqUserId", userId);
				param.put("eqWechatApplicationId", wechatApplicationId);
				count = wechatUserBaseInfoDao.selectCountByMap(param);
				if (count > 0) {
					throw new ServiceOperationException("该手机号码已经被绑定过");
				}
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 发送开发平台用户激活邮件
	 * 
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Response sendActivataAccountEmail(Request request) throws Exception  {
		DefaultResponse response = new DefaultResponse();
		try {
			OpenPlatformSendActivateEmailRequest sendActivateEmailRequest = (OpenPlatformSendActivateEmailRequest) request;
			String openId = sendActivateEmailRequest.getOpenId();
			Integer openPlatformId = sendActivateEmailRequest.getOpenPlatformId();
			String email = sendActivateEmailRequest.getEmail();
			Map<String, Object> cacheMap = (Map<String, Object>)cache.get(DataCacheKey.openPlatformInfoMapkey + "_" + openPlatformId + "_" + openId);
			if (cacheMap == null) {
				throw new ServiceOperationException("参数丢失");
			}
			String v = openId + "|" + openPlatformId + "|" + email;
			String p = StringUtil.base64Encode(v);
			String k = StringUtil.md5(v, PrivateKey.HAOYAO_PRIVATE_KEY.getValue());
//			mailingHelper.sendActivataAccountEmail(email, k, p);
			// 2个小时有效期
			cache.put(DataCacheKey.openPlatformActivateEmailMapkey + StringUtil.md5(openId + openPlatformId + email), k, 60*60*2);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	@Override
	public Response openPlatformLogin(Request request)  throws Exception {
		OpenPlatformLoginResponse response = new OpenPlatformLoginResponse();
		try {
			OpenPlatformLoginRequest openPlatformLoginRequest = (OpenPlatformLoginRequest) request;
			String ip = openPlatformLoginRequest.getIp();
			Integer openPlatformId = openPlatformLoginRequest.getOpenPlatformId();
			JSONObject object = JSONObject.parseObject(openPlatformLoginRequest.toString());
			
			// 获取openId（腾讯微博不用此操作）
			JSONObject openIdResult = platformOperationCenter.getOpenId(object);
			if (openIdResult.getIntValue(ApiConstants.RESULT_CODE) == ApiConstants.RESULT_FAIL) {
				throw new ServiceOperationException(openIdResult.getString(ApiConstants.RESULT_DESC));
			}
			String openId = openIdResult.getString(ApiConstants.OPEN_ID);
			String token = openIdResult.getString(ApiConstants.ACCESS_TOKEN);
			String refreshToken = openIdResult.getString(ApiConstants.REFRESH_TOKEN);
			Date expiresDate = openIdResult.getDate(ApiConstants.EXPIRES_DATE);
			// access_token 放到缓存
			Map<String, Object> cacheMap = new HashMap<String, Object>();
			cacheMap.put(ApiConstants.ACCESS_TOKEN, token);
			cacheMap.put(ApiConstants.REFRESH_TOKEN, refreshToken);
			cacheMap.put(ApiConstants.EXPIRES_DATE, expiresDate);
			cache.put(DataCacheKey.openPlatformInfoMapkey + "_" + openPlatformId + "_" + openId, cacheMap, 60*60*24);
			//通过openid查看是否已存在
			object.put(ApiConstants.OPEN_ID, openId);
			object.put(ApiConstants.ACCESS_TOKEN, token);
			object.put(ApiConstants.REFRESH_TOKEN, refreshToken);
			object.put(ApiConstants.EXPIRES_DATE, expiresDate);
			if (platformOperationCenter.isExistsOpenid(object)) {
				//修改token信息（公共实现）
				platformOperationCenter.updateTokenInfo(object);
				//登录（公共实现）
				Integer userId = object.getInteger(ApiConstants.USER_ID);
				UserAccountInfo userAccountInfo = userAccountInfoDao.selectById(userId);
				UserBaseAccountInfo userBaseAccountInfo = creatVerify(userAccountInfo, ip);
				response.setAccessToken(token);
				response.setExpiresDate(expiresDate);
				response.setIsBindOpenId(true);
				response.setOpenId(openId);
				response.setRefreshToken(refreshToken);
				response.setUserBaseAccountInfo(userBaseAccountInfo);
			} else {
				JSONObject result = platformOperationCenter.getNickName(object);
				if (result.getIntValue(ApiConstants.RESULT_CODE) == ApiConstants.RESULT_FAIL) {
					throw new ServiceOperationException(result.getString(ApiConstants.RESULT_DESC));
				}
				String nickName = result.getString(ApiConstants.NICK_NAME) == null ? "" : result.getString(ApiConstants.NICK_NAME);
				response.setNickName(nickName);
				response.setIsBindOpenId(false);
				response.setAccessToken(token);
				response.setExpiresDate(expiresDate);
				response.setOpenId(openId);
				response.setRefreshToken(refreshToken);
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Response bindOpenPlatformLogin(Request request) throws Exception  {
		OpenPlatformBindAndLoginResponse response = new OpenPlatformBindAndLoginResponse();
		OpenPlatformBindAndLoginRequest bindAndLoginRequest = (OpenPlatformBindAndLoginRequest) request;
		try {
			String openId = bindAndLoginRequest.getOpenId();
			Integer openPlatformId = bindAndLoginRequest.getOpenPlatformId();
			JSONObject object = JSONObject.parseObject(bindAndLoginRequest.toString());
			Map<String, Object> cacheMap = (Map<String, Object>)cache.get(DataCacheKey.openPlatformInfoMapkey + "_" + openPlatformId + "_" + openId);
			if (cacheMap == null) {
				throw new ServiceOperationException("参数丢失");
			}
			String token = (String) cacheMap.get(ApiConstants.ACCESS_TOKEN);
			String refreshToken = (String) cacheMap.get(ApiConstants.REFRESH_TOKEN);
			Date expiresDate = (Date) cacheMap.get(ApiConstants.EXPIRES_DATE);
			String ip = bindAndLoginRequest.getIp();
			this.bindOpenPlatformLoginAsync(bindAndLoginRequest);
			// 注册
			JSONObject result = platformOperationCenter.register(object);
			UserAccountInfo userAccountInfo = JSONObject.toJavaObject(result.getJSONObject("userAccountInfo"), UserAccountInfo.class);
			
			//登记openid（公共实现）
			UserOpenPlatformInfo userOpenPlatformInfo = new UserOpenPlatformInfo();
			userOpenPlatformInfo.setOpenId(openId);
			userOpenPlatformInfo.setOpenPlatformId(openPlatformId);
			userOpenPlatformInfo.setUserId(userAccountInfo.getId());
			userOpenPlatformInfo.setToken(token);
			userOpenPlatformInfo.setExpiresDate(expiresDate);
			userOpenPlatformInfo.setRefreshToken(refreshToken);
			userOpenPlatformInfoDao.insert(userOpenPlatformInfo);
			//登录（公共实现）
			UserBaseAccountInfo userBaseAccountInfo = creatVerify(userAccountInfo, ip);
			response.setUserBaseAccountInfo(userBaseAccountInfo);
			cache.remove(DataCacheKey.openPlatformInfoMapkey + "_" + openPlatformId + "_" + openId);
		} catch (Exception e) {
			bindAndLoginRequest.setPassword("******");
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
	
	/**
	 * 第三方注册同步锁
	 * 
	 */
	private synchronized void bindOpenPlatformLoginAsync(OpenPlatformBindAndLoginRequest bindAndLoginRequest)  throws Exception {
		StringBuilder cacheKey = new StringBuilder();
		cacheKey.append(DataCacheKey.bindOpenPlatformLoginAsyncMapkey);
		if (!StringUtil.isEmpty(bindAndLoginRequest.getOpenId())) {
			cacheKey.append("_").append(bindAndLoginRequest.getOpenId());
		}
		if (!StringUtil.isEmpty(bindAndLoginRequest.getPhone())) {
			cacheKey.append("_").append(bindAndLoginRequest.getPhone());
		}
		if (!StringUtil.isEmpty(bindAndLoginRequest.getEmail())) {
			cacheKey.append("_").append(bindAndLoginRequest.getEmail());
		}
		if (!StringUtil.isEmpty(bindAndLoginRequest.getUserName())) {
			cacheKey.append("_").append(bindAndLoginRequest.getUserName());
		}
		if (!StringUtil.isEmpty(bindAndLoginRequest.getNickName())) {
			cacheKey.append("_").append(bindAndLoginRequest.getNickName());
		}
		if (!StringUtil.isEmpty(bindAndLoginRequest.getIsRegister())) {
			cacheKey.append("_").append(bindAndLoginRequest.getIsRegister());
		}
		if (!StringUtil.isEmpty(bindAndLoginRequest.getIsphpw())) {
			cacheKey.append("_").append(bindAndLoginRequest.getIsphpw());
		}
		if (bindAndLoginRequest.getOpenPlatformId() > 0) {
			cacheKey.append("_").append(bindAndLoginRequest.getOpenPlatformId());
		}
		do {
			if(null != cache.get(cacheKey.toString())) {
				log.info("func[bindOpenPlatformLoginAsync] 用户注册操作进程未完成，请求频率过频繁");
				throw new ServiceOperationException("该请求正在进行中，请稍等");
			} else {
				cache.put(cacheKey.toString(), 3, 3);
				return;
			}
		}while(true);
	}
	
	/**
	 * 用户信息列表接口
	 */
	@Override
	public Response listUserAccount(Request request) throws Exception{
		UserAccountInfoListRequest listRequest = (UserAccountInfoListRequest)request;
		
		Map<String,Object> params = new HashMap<String,Object>();
		if(!StringUtil.isEmpty(listRequest.getEmail())) {
			params.put("eqEmail", listRequest.getEmail());
			params.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
		}
		
		if(!StringUtil.isEmpty(listRequest.getPhone())) {
			params.put("eqPhone", listRequest.getPhone());
			params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
		}
		
		if(!StringUtil.isEmpty(listRequest.getIds())) {
			params.put("inIdList", listRequest.getIds().split(","));
		}
		
		if(!StringUtil.isEmpty(listRequest.getRealName())) {
			params.put("eqRealName", listRequest.getRealName());
		}
		
		if(!StringUtil.isEmpty(listRequest.getEndTime()) && !StringUtil.isEmpty(listRequest.getStartTime())) {
			params.put("gtCreateTime", DateUtil.parseDate(DateUtil.formatDate(DateUtil.parseDate(listRequest.getStartTime()), "yyyy-MM-dd") +  " 00:00:00", "yyyy-MM-dd HH:mm:ss").getTime());
			params.put("ltCreateTime", DateUtil.parseDate(DateUtil.formatDate(DateUtil.parseDate(listRequest.getEndTime()), "yyyy-MM-dd") +  " 23:59:59", "yyyy-MM-dd HH:mm:ss").getTime());
		}
		
		if(listRequest.getAgeLower() > 0) {
			params.put("gtAge", listRequest.getAgeLower());
		}
		if(listRequest.getAgeUpper() > 0) {
			params.put("ltAge", listRequest.getAgeUpper());
		}
		
		if(!StringUtil.isEmpty(listRequest.getExpandCode())) {
			params.put("eqExpandCode", listRequest.getExpandCode());
		}
		
		if(!StringUtil.isEmpty(listRequest.getAccountName())) {
			params.put("eqAccountName", listRequest.getAccountName());
		}
		
		try {
			PageList<UserBaseAccountInfo> userList = userAccountInfoDao.selectByParam(params, listRequest.getPageNum(), listRequest.getPageSize(),true);
			PageListResponse<UserBaseAccountInfo> listResponse = new PageListResponse<UserBaseAccountInfo>();
			listResponse.setList(userList);
			listResponse.setPageTurn(userList.getPageTurn());
			listResponse.setTip("查询列表成功");
			return listResponse;
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	@Override
	public Response updateAuthorization(Request request) {
		DefaultResponse response = new DefaultResponse();
		try {
			UserAccountAuthorizationUpdateRequest userAccountAuthorizationUpdateRequest = (UserAccountAuthorizationUpdateRequest) request;
			int userId = userAccountAuthorizationUpdateRequest.getUserId();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			params.put("isAuthorized", UserAccountAuthorizedStatusEnum.YES.getId());
			int count = userAccountInfoDao.updateByMap(params);
			if (count < 1) {
				throw new ServiceOperationException("更新失败");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	@Override
	public Response updateNovice(Request request) {
		DefaultResponse response = new DefaultResponse();
		try {
			UserAccountNoviceUpdateRequest userAccountNoviceUpdateRequest = (UserAccountNoviceUpdateRequest) request;
			int userId = userAccountNoviceUpdateRequest.getUserId();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			params.put("isNovice", UserAccountAuthorizedStatusEnum.NO.getId());
			int count = userAccountInfoDao.updateByMap(params);
			if (count < 1) {
				throw new ServiceOperationException("更新失败");
			}
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	@Override
	public Response obtainAuthorization(Request request) {
		ShowResponse<UserAccountInfo> response = new ShowResponse<UserAccountInfo>();
		try {
			UserAccountAuthorizationUpdateRequest userAccountAuthorizationRequest = (UserAccountAuthorizationUpdateRequest) request;
			int userId = userAccountAuthorizationRequest.getUserId();
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqId", userId);
			PageList<UserAccountInfo> list = userAccountInfoDao.selectByMap(params, false);
			if (list!=null && list.size() > 0) {
				response.setInfo(list.get(0)); 
			}
		}catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}
}
